/*
 * Copyright 2013 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 */
package com.madding.shared.encrypt.cert.self.loader;

import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;

import com.madding.shared.encrypt.cert.exception.TDCertException;
import com.madding.shared.encrypt.cert.self.tool.PrivateKeyTool;
import com.madding.shared.encrypt.cert.self.tool.X509CertTool;
import com.madding.shared.encrypt.constants.Charset;
import com.madding.shared.encrypt.io.StreamUtil;
import com.madding.shared.lang.ClassLoaderUtil;

/**
 * 类CaCertLoader.java的实现描述：TODO 类实现描述
 * 
 * @author madding Dec 6, 2013 11:33:10 PM
 */
public class CaCertLoader {

    private static final String CA_CRT_FILE = "META-INF/self_certca/ca.crt";
    private static final String CA_KEY_FILE = "META-INF/self_certca/ca.key";

    private static Certificate  cert;
    private static PrivateKey   cakPrivKey;

    public synchronized static Certificate getCaCrt() throws TDCertException, CertificateException, IOException {
        if (cert == null) {
            ClassLoader classLoader = ClassLoaderUtil.getClassLoader();
            InputStream is = classLoader.getResourceAsStream(CA_CRT_FILE);
            String b64PrivKey = StreamUtil.stream2Bytes(is, Charset.UTF_8);
            cert = X509CertTool.coverString2Cert(b64PrivKey);
        }
        return cert;
    }

    public synchronized static PrivateKey getCaKey() throws TDCertException {
        if (cakPrivKey == null) {
            ClassLoader classLoader = ClassLoaderUtil.getClassLoader();
            InputStream is = classLoader.getResourceAsStream(CA_KEY_FILE);
            String b64PrivKey = StreamUtil.stream2Bytes(is, Charset.UTF_8);
            cakPrivKey = PrivateKeyTool.coverString2PrivateKey(b64PrivKey);
        }
        return cakPrivKey;
    }
}
